package voliatile;

import java.util.concurrent.atomic.AtomicInteger;

//不保证原子性 不使用lock和syncronized情况下，可把int类型转变为AtomicInteger对象可保证安全
public class Demo2 {
    //    private volatile static int num = 0;
    private volatile static AtomicInteger num = new AtomicInteger();

    public static void main(String[] args) {
        for (int i = 1; i <= 20; i++) {
            new Thread(() -> {
                for (int j = 1; j <= 1000; j++) {
                    add();
                }
            }).start();
        }
        while (Thread.activeCount() > 2) {//只剩下GC和main线程
            Thread.yield();
        }
        System.out.println(num);

    }


    //    public static void add(){
//        num++;
//    }
    public static void add() {
        num.getAndIncrement();
    }
}
